package com.geekaca.chat;

import javax.swing.*;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ClientReader implements Runnable {
    private Socket socket;
    private ClientChat clientChat;
    private StringBuilder sb;

    public ClientReader(Socket socket, ClientChat clientChat, StringBuilder sb) {
        this.socket = socket;
        this.clientChat = clientChat;
//        this.smsContent = smsContent;
        this.sb = sb;
//        this.onLineUsersJList = onLineUsersJList;
    }

    @Override
    public void run() {
        try {
            InputStream ips = socket.getInputStream();
            DataInputStream dis = new DataInputStream(ips);
//            OutputStream ops = socket.getOutputStream();
//            BufferedReader br = new BufferedReader(new InputStreamReader(ips));

            while (true) {
                int msgType = dis.readInt();
                switch (msgType) {
                    case ChatConstants.MSG_TYPE_LOGIN:
                        String names = dis.readUTF();
                        System.out.println(names);
                        String[] splits = names.split(ChatConstants.SPLIT);
                        System.out.println("splits length = " + splits.length);
                        clientChat.onLineUsersJList.setListData(splits);
                        break;

                    case ChatConstants.MSG_TYPE_CHAT:
                        String chat = dis.readUTF();
                        sb.append(chat + "\n");
                        System.out.println(chat);
                        clientChat.smsContent.setText(sb.toString());
                        clientChat.smsContent.setCaretPosition(clientChat.smsContent.getText().length());
                        break;

                    case ChatConstants.MSG_TYPE_CHAT_PRIVATE:
                        System.out.println("收到私聊");
                        String privateChat = dis.readUTF();
                        sb.append( privateChat+ "\n");
                        System.out.println(privateChat);
                        clientChat.smsContent.setText(sb.toString());
                        clientChat.smsContent.setCaretPosition(clientChat.smsContent.getText().length());
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
